var ws = null; //建立的连接
var url = null;
var lockReconnect = false; //是否真正建立连接
var timeout = 30 * 1000; //30秒一次心跳
var timeoutObj = null; //心跳心跳倒计时
var serverTimeoutObj = null; //心跳倒计时
var timeoutnum = null; //断开 重连倒计时
var global_callback = null; //监听服务端消息
// uri: 长链接地址<br>// jwt: 前后端连接凭证， 按需添加<br>// callback: 服务端消息回调函数
export function createWebscoket(uri, callback) {
 // console.log(uri, callback);
  global_callback = callback;
  url = uri;
  ws = new WebSocket(uri);
  ws.onopen = () => {
    lockReconnect = true;
   // console.log("链接上了");
    //开启连接心跳
    start();
  };
  ws.onmessage = onMessage;
  ws.onerror = onError;
  ws.onclose = onClose;
  ws.onsend = onSend;
}

//发送消息
export function onSend(message) {
 // console.log(`发送消息： ${message}`);
  ws.send(message);
}

//接受服务端消息
export function onMessage(res) {
  let msgData = res.data;
  if (typeof msgData != "object" && msgData != "Connect success") {
    var data = msgData.replace(/\ufeff/g, "");
    var message = JSON.parse(data);
    //服务端消息回掉
    global_callback(message);
    //重置心跳
    reset();
  }
}

//连接失败
export function onError() {
 // console.log("连接失败");
  ws?.close();
  ws = null;
  lockReconnect = false;
}

//连接关闭
export function onClose() {
 // console.log("连接关闭");
}
//断开关闭
export function closeWs() {
 // console.log(lockReconnect, '切换模块关闭');
  if (lockReconnect) {
    ws.close();
    ws = null;
    lockReconnect = false;
  }
}

// 发送心跳
export function start() {
  timeoutObj && clearTimeout(timeoutObj);
  serverTimeoutObj && clearTimeout(serverTimeoutObj);
  timeoutObj = setTimeout(function () {
    //这里发送一个心跳，后端收到后，返回一个心跳消息
    //// console.log(ws.readyState == 1, "心跳");
    if (ws?.readyState == 1) {
      //如果连接正常
      ws.send(JSON.stringify({ type: "ping" }));
    } else {
      //否则重连
      reconnect();
      return;
    }
    serverTimeoutObj = setTimeout(function () {
      //超时关闭
      ws?.close();
      // reconnect();
    }, timeout);
  }, timeout + 3000);
}
//重置心跳
export function reset() {
  var that = this;
  //清除时间
  clearTimeout(timeoutObj);
  //清除时间
  clearTimeout(serverTimeoutObj);
  start(); //重启心跳
}

//重新连接
export function reconnect() {
 // console.log(lockReconnect, "重新连接");
  if (lockReconnect) {
    return;
  }
  lockReconnect = true;
  //没连接上会一直重连，设置延迟避免请求过多
  timeoutnum && clearTimeout(timeoutnum);
  timeoutnum = setTimeout(function () {
    createWebscoket(url, global_callback); //新连接
    lockReconnect = false;
  }, 5000);
}
